#include "mywidget.h"
#include <QHBoxLayout>
#include <QApplication>
#include <QDesktopWidget>
#include <QQmlEngine>
#include <QQmlContext>
#include <QMenu>

MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
    m_view = new QQuickWidget(this);
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->addWidget(m_view);

    setLayout(layout);

    m_view->engine()->rootContext()->setContextProperty("widget",this);

    m_view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));

    this->setWindowFlags(this->windowFlags() | Qt::SubWindow | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);//窗口置顶，无边框
    setAttribute(Qt::WA_TranslucentBackground);
    setAutoFillBackground(true);//填充背景

    QPalette palette;
    palette.setBrush(QPalette::Window, QBrush(QColor(Qt::transparent)));
    this->setPalette(palette);

    m_view->setClearColor(QColor(Qt::transparent));    //qml 透明

    this->setFixedSize(QApplication::desktop()->width(),QApplication::desktop()->height()-1);

    /*鼠标穿透*/
    SetWindowLong((HWND)winId(), GWL_EXSTYLE, GetWindowLong((HWND)winId(), GWL_EXSTYLE) |
                       WS_EX_TRANSPARENT | WS_EX_LAYERED);

    setSystemMenu();

    m_thread = new QueryKeyThread(this);
    connect(m_thread, &QueryKeyThread::queryResult, this, &MyWidget::queryResult);
    connect(m_thread, &QueryKeyThread::mousePointChanged, this, &MyWidget::mousePointChanged);
    m_thread->start();
}

void MyWidget::setSystemMenu()
{
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/logo.ico"));

    QMenu *menu = new QMenu(this);

    QAction *action = menu->addAction("退出");
    connect(action, &QAction::triggered, this, &MyWidget::systemExit);

    trayIcon->setContextMenu(menu);
    trayIcon->show();
}

void MyWidget::queryResult(QString name)
{
//    qInfo() << __FUNCTION__ << name;
//    qInfo() << __FUNCTION__ << gMouseX << "," << gMouseY;
//    static int lastX{ 0 };
//    static int lastY{ 0 };
//    if(lastX != gMouseX || lastY != gMouseY)
//    {
//        lastX = gMouseX;
//        lastY = gMouseY;
        emit notifyMsg(gMouseX, gMouseY);
//    }
}


void MyWidget::mousePointChanged(int x, int y)
{
    emit notifyMousePos(x, y);
}

void MyWidget::systemExit(bool b)
{
    (void)b;
    qApp->quit();
}
